import React, { useState, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Layout, Menu } from 'antd'
import {
  HomeOutlined,
  UserOutlined,
  CrownOutlined,
  UnorderedListOutlined,
  AuditOutlined,
  NotificationOutlined
} from '@ant-design/icons'
import style from './index.module.css'
import { getMenuApi } from '@/api/menu'
import { connect } from 'react-redux'

function SideMenu(props) {
  const { Sider } = Layout
  const navigate = useNavigate()
  const [menu, setMenu] = useState([])
  const location = useLocation()
  const defaultMenuKey = [location.pathname]
  const openKeys = ['/' + location.pathname.split('/')[1]]
  const { role: { rights }} = JSON.parse(localStorage.getItem('token'))

  useEffect(() => {
    getMenuApi({ '_embed': 'children' }).then(res => {
      const newList = recurrenceTree(res)
      setMenu(newList)
    })
  }, [])

  // 递归处理
  const recurrenceTree = (data) => {
    const newArr = []
    data.forEach(item => {
      if (item.pagepermisson === 1 && rights.includes(item.key)) {
        if (item.children?.length > 0) {
          newArr.push({
            key: item.key,
            label: item.title,
            icon: iconList[item.key],
            children: recurrenceTree(item.children)
          })
        } else {
          newArr.push({
            key: item.key,
            label: item.title,
            icon: iconList[item.key]
          })
        }
      }
    })
    return newArr
  }

  const iconList = {
    '/home': <HomeOutlined />,
    '/user-manage': <UserOutlined />,
    '/right-manage': <CrownOutlined />,
    '/news-manage': <UnorderedListOutlined />,
    '/audit-manage': <AuditOutlined />,
    '/publish-manage': <NotificationOutlined />
  }

  return (
    <Sider collapsed={props.isCollapsed} collapsible trigger={null}>
      <div style={{
        display: 'flex',
        height: '100%',
        flexDirection: 'column'
      }}>
        <div className={style.logo}>大狮子</div>
        <div style={{
          flex: 1,
          overflow: 'auto'
        }}>
          <Menu
            defaultOpenKeys={openKeys}
            items={menu}
            mode="inline"
            onClick={({ key }) => {
              navigate(key)
            }}
            selectedKeys={defaultMenuKey}
            theme="dark"
          />
        </div>
      </div>
    </Sider>
  )
}

const mapStateToProps = (state) => {
  return {
    isCollapsed: state.CollapseReducer.isCollapsed
  }
}

export default connect(mapStateToProps)(SideMenu)